package com.qys.livesMall.anchor.controller.app;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qys.livesMall.anchor.model.entity.AnchorAccessRecord;
import com.qys.livesMall.anchor.model.vo.AnchorAccessRecordVO;
import com.qys.livesMall.anchor.service.AnchorAccessRecordService;
import com.qys.livesMall.app.user.model.entity.H2AppUser;
import com.qys.livesMall.app.user.service.IH2AppUserService;
import com.qys.livesMall.common.result.R;
import com.qys.livesMall.framework.utils.SecurityUtils;
import com.qys.livesMall.framework.view.BaseQuery;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

/**
 * 主播访问记录表(AnchorAccessRecord)表控制层
 *
 * @author makejava
 * @since 2023-07-13 16:41:55
 */
@RestController
@RequestMapping("/app/anchorAccessRecord")
@RequiredArgsConstructor
@Tag(name = "App-主播访客记录", description = "App-主播访客记录")
public class AppAnchorAccessRecordController {

    private final AnchorAccessRecordService anchorAccessRecordService;
    private final IH2AppUserService userService;

    /**
     * 通过主键查询单条数据
     *
     * @param dto 查询实体
     * @return 单条数据
     */
    @PostMapping("/getVisitor")
    @Operation(summary = "主播查询访客记录")
    public R<IPage<AnchorAccessRecordVO>> selectOne(@RequestBody BaseQuery dto) {
        IPage<AnchorAccessRecordVO> page = anchorAccessRecordService.page(new Page<>(dto.getPageNum(), dto.getPageSize()),
                        Wrappers.<AnchorAccessRecord>lambdaQuery().eq(AnchorAccessRecord::getAnchorId, SecurityUtils.getUserId()).groupBy(AnchorAccessRecord::getVisitorId).orderByDesc(AnchorAccessRecord::getCreateTime))
                .convert(e -> {
                    AnchorAccessRecordVO recordVO = new AnchorAccessRecordVO();
                    recordVO.setUserId(e.getVisitorId());
                    recordVO.setCreateTime(e.getCreateTime());
                    H2AppUser appUser = userService.getById(recordVO.getUserId());
                    if (null != appUser) {
                        recordVO.setUserAvatar(appUser.getAvatar());
                        recordVO.setUserName(appUser.getUserName());
                    }
                    return recordVO;
                });
        return R.ok(page);
    }

    /**
     * 新增记录（访问主播）
     *
     * @param userId 被访问主播的userId
     * @return 新增结果
     */
    @PostMapping("/visit/{userId}")
    @Operation(summary = "新增记录（访问主播）")
    public R<?> insert(@PathVariable String userId) {
        AnchorAccessRecord anchorAccessRecord = new AnchorAccessRecord();
        anchorAccessRecord.setAnchorId(Long.valueOf(userId));
        anchorAccessRecord.setVisitorId(SecurityUtils.getUserId());
        anchorAccessRecordService.save(anchorAccessRecord);
        return R.ok();
    }
}

